<template>
  <div v-if="cartList.length>0">
    <el-row class="title">
      <el-col :span="3">
        <el-checkbox label="全选"
                     :indeterminate="halfState"
                     v-model="checkAllState" @change="checkAllOrNone"/>
      </el-col>
      <el-col :span="10">商品</el-col>
      <el-col :span="2">单价</el-col>
      <el-col :span="5">数量</el-col>
      <el-col :span="2">小计</el-col>
      <el-col :span="2">操作</el-col>
    </el-row>
    <el-row v-for="(cart,index) in cartList" :key="index" class="cartItem">
      <el-col :span="2">
        <el-checkbox v-model="cart.checkState" @change="changeState"/>
      </el-col>
      <el-col :span="2">
        <el-image style="width: 50px;height: 50px"
                  :src="server + '/goods/pic/' +cart.goods.picList[0].url"
                  fit="contain"/>

      </el-col>
      <el-col :span="5">{{ cart.goods.name }}</el-col>
      <el-col :span="4">{{ cart.goods.color }}-{{ cart.goods.version }}</el-col>
      <el-col :span="2">{{ cart.goods.price }}</el-col>
      <el-col :span="5">
        <el-input-number v-model="cart.count"
                         :min="1"
                         size="small"
                         @change="updateCount(cart)"/>
      </el-col>
      <el-col :span="2">{{ cart.goods.price * cart.count }}</el-col>
      <el-col :span="1">
        <el-button type="danger" :icon="Delete" circle @click="deleteById(cart.id)"/>
      </el-col>
    </el-row>
    <el-row class="cartFooter">
      <el-col :span="2">
        <el-checkbox label="全选"
                     :indeterminate="halfState"
                     v-model="checkAllState" @change="checkAllOrNone"/>
      </el-col>
      <el-col :span="4" @click="deletePart">
        <el-button type="danger" link>删除选中的商品</el-button>
      </el-col>
      <el-col :span="8" @click="deleteAll">
        <el-button type="danger" link>清理购物车</el-button>
      </el-col>
      <el-col :span="4">已选择{{ checkedCount }}件商品</el-col>
      <el-col :span="4">￥{{ total }}</el-col>
      <el-col :span="2">
        <el-button type="danger" @click="toCreateOrderPage">结算</el-button>
      </el-col>
    </el-row>
  </div>
  <div v-else class="none">
    <div>你的购物车像你的人生一样,空空如也~~~</div>
    <div>
      <RouterLink to="/user/index">点我丰富人生</RouterLink>
    </div>
  </div>
</template>
<script setup>
import {ref} from "vue";
import cartApi from "@/api/cartApi.js";
import {Delete, ShoppingCartFull} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import router from "@/router/index.js";

const server = ref(import.meta.env.VITE_SERVER_ADDR)
//保存当前用户所有的购物车信息
const cartList = ref([])
//全选按钮是否选中
const checkAllState = ref(false)
//没有全选的状态
const halfState = ref(false)
//选中商品的数量
const checkedCount = ref(0)
//选中商品的金额
const total = ref(0)
//跳转到生成订单的页面
function toCreateOrderPage(){
  //获取已经选中的购物车id
  let cartIds=[]
  cartList.value.forEach(cart=>{
    if (cart.checkState){
      cartIds.push(cart.id)
    }
  })
  if (cartIds.length===0){
    ElMessage.warning("没选商品啊，结不了")
    return
  }
  router.push({
    path:"/user/createOrder",
    query:{
      cartIds
    }
  })
}
//删除所选的内容
function deletePartt() {
  let ids = [];
  cartList.value.forEach(cart => {
    if (cart.checkState) {
      ids.push(cart.id)
    }
  });
  cartApi.deleteByIds(ids).then(resp => {
    if (resp.code === 10000) {
      ElMessage.success(resp.msg)
      //将被删除的项从cartList中清除
      cartList.value = cartList.value.filter(cart => !cart.checkState)
      //重新设置全选按钮的状态，重新计算金额和数量
      checkStateChange()
    } else {
      ElMessage.error(resp.msg)
    }
  })
}

function deletePart() {
  if (checkedCount.value === 0) {
    ElMessage.error("不满足删除条件，无法删除")
  }
  cartList.value.forEach(cart => {
    if (cart.checkState) {
      cartApi.delete(cart.id)
          .then(resp => {
            if (resp.code === 10000) {
              checkAllState.value = false
            }
          })
    }
  })
  cartList.value = cartList.value.filter(cart => cart.checkState !== true);
  //cartList.value.forEach(cart => cart.checkState = false)
  checkAllOrNone()
}

//清空购物车
function deleteAll1() {
  let ids = []
  cartList.value.forEach(cart => {
    ids.push(cart.id)
  })
  if (ids.length === 0) {
    ElMessage.warning("删不了啊，没东西啊");
  }
  //批量删除
  cartApi.deleteByIds(ids)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success("清除成功");
          //重新获取购物车列表
          selectCartList()
        } else {
          ElMessage.error("清除成功");
        }
      })
}

function deleteAll() {
  if (cartList.value.length === 0) {
    ElMessage.error("购物车为空,无法清空")
  } else {
    ElMessageBox.confirm(
        '确定要全部清空嘛???',
        'Point',
        {
          confirmButtonText: '确定',
          cancelButtonText: '下次一定',
          type: 'warning',
        }
    )
        .then(() => {//点击确定按钮的回调
          cartList.value.forEach(cart => {
            cartApi.delete(cart.id)
                .then(resp => {
                  if (resp.code === 10000) {
                    //ElMessage.success("清除成功");
                  }
                })
          })
          //设置全选按钮的状态
          changeState();
          checkAllOrNone()
          cartList.value = {}
          //checkAllState.value = 0
        })
  }
}

//全选--全不选
function checkAllOrNone() {
  //让每个购物车项前面的多选按钮的状态和全选按钮的状态保持一致
  cartList.value.forEach(cart => {
    cart.checkState = checkAllState.value
    halfState.value = false
  })
  getCountAndTotal()
}

//购物车项前面的多选按钮发生状态变化时调用的函数
function changeState() {
  /*
  * 设置全选按钮
  * 1.如果所有的checkState都被选中，则设置全选按钮选中
  * 2.如果所有的checkState都没被选中，则设置全选按钮不选中
  * */
  let count = 0;
  checkedCount.value = 0
  total.value = 0
  cartList.value.forEach(cart => {
    if (cart.checkState) {
      count++
    }
  })
  if (count === cartList.value.length) {
    checkAllState.value = true
    halfState.value = false
  } else if (count === 0) {
    checkAllState.value = false
    halfState.value = false
  } else {
    halfState.value = true
    checkAllState.value = false
  }
  getCountAndTotal()
}

//计算选中的商品的数量与金额
function getCountAndTotal() {
  checkedCount.value = 0
  total.value = 0
  cartList.value.forEach(cart => {
    if (cart.checkState) {
      checkedCount.value += cart.count//计算选中的商品的数量
      total.value += cart.goods.price * cart.count//计算选中的商品的金额
    }
  })
}

//查询当前用户所有的购物车信息
function selectCartList() {
  cartApi.selectCartList()
      .then(resp => {
        //console.log(resp.data)
        cartList.value = resp.data
        cartList.value.forEach(cart => cart.checkState = false)
      })
}

//根据id删除
function deleteById(id) {
  cartApi.delete(id)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
          //将被删除的项从cartList中清除
          //留下card_id与被删除的id不相等的数据,除去删除掉的数据
          cartList.value = cartList.value.filter(cart => cart.id != id);
          changeState()//设置全选按钮的状态
        } else {
          ElMessage.error(resp.msg)
        }
      })
  getCountAndTotal()
}

//修改购物车商品的数量
function updateCount(cart) {
  const cartInfo = {
    id: cart.id,
    count: cart.count,
  }
  cartApi.update(cartInfo)
      .then(resp => {
        if (resp.code === 10000) {
          //让购物车中商品的数量和数据库中保持一致
          cartApi.selectById(cartInfo.id)
              .then(resp => {
                cartList.value.forEach(cart => {
                  if (cart.id === cartInfo.id) {
                    cart.count = resp.data.count
                  }
                });
              })
        } else {
          ElMessage.error(resp.msg)
        }
      })
  getCountAndTotal()
}

selectCartList()

</script>

<style scoped>
.title {
  font-size: 14px;
  padding-left: 20px;
  background-color: aquamarine;
  line-height: 30px;
  height: 40px;
  margin-bottom: 10px;
}

.cartItem {
  background-color: aqua;
  padding-left: 20px;
  font-size: 14px;
  border-bottom: 1px solid #eeeeee;
  margin-bottom: 10px;
  line-height: 50px;
  height: 50px;
}

.cartFooter {
  font-size: 14px;
  padding-top: 4px;
  padding-left: 20px;
  background-color: burlywood;
  line-height: 30px;
  height: 40px;
}

.none {
  font-weight: bold;
  font-size: 20px;
  margin-top: 100px;
  height: 200px;
  text-align: center;
}

</style>